import React, { JSX } from 'react';
import { Outlet, useNavigate } from 'react-router-dom';
import { useAppDispatch, useAppSelector } from '../../actions/hooks';
import { authActions, selectLoggedIn, selectTokenLoaded } from '../../actions/Auth';
import { globalActions, selectGlobalAlert, selectGlobalAlertMessage, selectGlobalAlertTitle, selectGlobalAlertType } from '../../actions/Global';
import { AlertBox } from '../../components/AlertBox';

function Framework(): JSX.Element {

  const isLoggedIn = useAppSelector(selectLoggedIn);
  const isTokenLoaded = useAppSelector(selectTokenLoaded);

  const openAlert = useAppSelector(selectGlobalAlert);
  const alertTitle = useAppSelector(selectGlobalAlertTitle);
  const alertMessage = useAppSelector(selectGlobalAlertMessage);
  const alertType = useAppSelector(selectGlobalAlertType);

  const dispatch = useAppDispatch();
  const navigate = useNavigate();

  React.useEffect(() => {
    dispatch(authActions.loadToken());
  });

  React.useEffect(() => {
    if (isTokenLoaded && !isLoggedIn) {
      navigate('/login');
    }
  }, [navigate, isTokenLoaded, isLoggedIn]);

  return (
    <>
      {isLoggedIn &&
        <Outlet />
      }
      <AlertBox
        open={openAlert}
        onClose={() => { dispatch(globalActions.closeAlert()); }}
        title={alertTitle}
        message={alertMessage}
        severity={alertType}
      />
    </>
  );
}

export default Framework;